<template>
    <div class="newPrimaryClass">
        <div class="newPrimaryClass_top">
			<div class="into_index">首页<i class="el-icon-close"></i></div>
			<div class="current">{{text}}<i class="el-icon-close"></i></div>
		</div>
        <!-- 商家类型与返回 -->
        <div class="newPrimaryClass_type">
            <div>待处理/<span class="text">{{text}}</span></div>
            <el-button @click="toBack" type="success">返回</el-button>
        </div>

        <!-- 基础信息 -->
        <div class="contentBox">
            <h3>基础信息</h3>
            <div class="boxBig">
                <div class="item">
                    <div class="tit">业主姓名</div>
                    <el-input style="width:40%;" placeholder="请输入业主姓名" class="input" type="text" v-model="form.realname"></el-input>
                </div>
                <div class="item">
                    <span class="tit">手机号码</span>
                    <el-input style="width:40%;" placeholder="请输入手机号码" class="input" type="number" v-model="form.phone"></el-input>
                </div>
            </div>
            <div class="boxBig">
                <div class="item">
                    <div class="tit">户型</div>
                    <el-input style="width:40%;" placeholder="请输入户型" class="input" type="text" v-model="form.house_type"></el-input>
                </div>
                <div class="item">
                    <span class="tit">面积</span>
                    <el-input style="width:40%;" placeholder="请输入面积" class="input" type="number" v-model="form.house_area"></el-input>m²
                </div>
            </div>
            <div class="boxBig">
                <div class="item">
                    <div class="tit">小区</div>
                    <el-input style="width:40%;" placeholder="请输入小区" class="input" type="text" v-model="form.estate"></el-input>
                </div>
            </div>
            <div class="item">
				<div class="tit">施工地址</div>
				<el-select v-model="provinceObj" @change="select1" value-key="cityid" placeholder="请选择省份">
					<el-option
					v-for="item in province"
					:key="item.cityid"
					:label="item.city_name"
					:value="{cityid:item.cityid,city_name:item.city_name}">
					</el-option>
				</el-select>
				<el-select v-model="cityObj" @change="select2" value-key="cityid" placeholder="请选择城市">
					<el-option
					v-for="item in city"
					:key="item.cityid"
					:label="item.city_name"
					:value="{cityid:item.cityid,city_name:item.city_name}">
					</el-option>
				</el-select>
				<el-select v-model="districtObj" @change="select3" value-key="cityid" placeholder="请选择县区">
					<el-option
					v-for="item in district"
					:key="item.cityid"
					:label="item.city_name"
					:value="{cityid:item.cityid,city_name:item.city_name}">
					</el-option>
				</el-select>
				<el-select v-model="streetObj" @change="select4" value-key="cityid" placeholder="请选择街道">
					<el-option
					v-for="item in street"
					:key="item.cityid"
					:label="item.city_name"
					:value="{cityid:item.cityid,city_name:item.city_name}">
					</el-option>
				</el-select>
                <el-input style="width:27%;" v-model="form.address" placeholder="请输入楼盘详细地址"></el-input>
			</div>
			<div class="item">
				<div class="tit">施工诉求</div>
				<el-input type="textarea"  v-model="form.remark" style="width:70%" rows="5"></el-input>
			</div>
        </div>
		<!-- 基础信息 -->
        <div class="contentBox">
            <h3>施工信息</h3>
            <div class="boxBig">
                <div class="item">
                    <div class="tit">管家</div>
                    <div class="position">
						<el-input type="text" v-model="house_keeper.name" readonly placeholder="请选择"></el-input>
						<el-input type="number" v-model="house_keeper.phone" readonly placeholder=""></el-input>
						<el-button type="primary" @click="selectKeeper">选择</el-button>
					</div>
                </div>
                <div class="item">
                    <span class="tit">工长</span>
                    <div class="position">
						<el-input type="text" v-model="foreman.name" readonly placeholder="请选择"></el-input>
						<el-input type="number" v-model="foreman.phone" readonly placeholder=""></el-input>
						<el-button type="primary" @click="selectForeman">选择</el-button>
					</div>
                </div>
            </div>
			<div class="item">
				<div class="tit">施工时间</div>
				<el-date-picker
					v-model="constrTime"
					type="daterange"
					range-separator="至"
					start-placeholder="开始日期"
					end-placeholder="结束日期">
				</el-date-picker>
			</div>
			<div class="item">
				<div class="tit">施工合同</div>
				<!-- <el-input class="itemIpt" type="file"></el-input> -->
                <el-upload
                    action="/api/client/base/uploadfile"
                    list-type="picture-card"
                    :on-success="handleEstateSuccess1"
                    :on-preview="handlePictureCardPreview1"
                    :headers="myHeaders"
                    :file-list="fileList1"     
                    :before-upload="beforeAvatarUpload1"         
                    :limit="10" 
                    :auto-upload="true"
                    :on-remove="handleRemove1">
                    <i class="el-icon-plus"></i>
                </el-upload>
                <el-dialog :visible.sync="dialogVisible1">
                    <img width="100%" :src="dialogImageUrl1" alt="">
                </el-dialog>
			</div>
			<div class="item">
				<div class="tit">施工图纸</div>
                <el-upload
                    action="/api/client/base/uploadfile"
                    list-type="picture-card"
                    :on-success="handleEstateSuccess"
                    :on-preview="handlePictureCardPreview"
                    :headers="myHeaders"
                    :file-list="fileList"     
                    :before-upload="beforeAvatarUpload"         
                    :limit="10" 
                    :auto-upload="true"
                    :on-remove="handleRemove">
                    <i class="el-icon-plus"></i>
                </el-upload>
                <el-dialog :visible.sync="dialogVisible">
                    <img width="100%" :src="dialogImageUrl" alt="">
                </el-dialog>
			</div>
			<div class="item" v-if="form.decoration_id">
				<div class="tit">设计图纸</div>
                <el-upload
                    action="/api/client/base/uploadfile"
                    list-type="picture-card"
                    :on-success="handleEstateSuccess_desgin"
                    :on-preview="handlePictureCardPreview_desgin"
                    :headers="myHeaders"
                    :file-list="fileList_desgin"     
                    :before-upload="beforeAvatarUpload_desgin"         
                    :limit="10" 
                    :auto-upload="true"
                    :on-remove="handleRemove_desgin">
                    <i class="el-icon-plus"></i>
                </el-upload>
                <el-dialog :visible.sync="dialogVisible_desgin">
                    <img width="100%" :src="dialogImageUrl_desgin" alt="">
                </el-dialog>
			</div>
			<div class="item">
				<div class="tit">选材单</div>
                <el-upload
                    action="/api/client/base/uploadfile"
                    list-type="picture-card"
                    :on-success="handleEstateSuccess_mater"
                    :on-preview="handlePictureCardPreview_mater"
                    :headers="myHeaders"
                    :file-list="fileList_mater"     
                    :before-upload="beforeAvatarUpload_mater"         
                    :limit="10" 
                    :auto-upload="true"
                    :on-remove="handleRemove_mater">
                    <i class="el-icon-plus"></i>
                </el-upload>
                <el-dialog :visible.sync="dialogVisible_mater">
                    <img width="100%" :src="dialogImageUrl_mater" alt="">
                </el-dialog>
			</div>
			<div class="item">
				<div class="tit">合同金额</div>
				<el-input class="itemIpt" v-model="form.contract_price" type="number"></el-input>元
			</div>
			<div class="itemPay">
				<h4>支付次数和比例</h4>
				<div class="payList">
                    <div class="item" v-for="(item,index) in payNumList" :key="index">
                        <span>{{index+1}}</span>
                        <el-input v-model="item.propor" @input="proporInput(index)" type="number" placeholder="请输入比例"></el-input>%
                        <div class="proporPrice">￥{{(form.contract_price*(item.propor/100)).toFixed(2)}}</div>
                        <img src="../../../../../assets/orderPlus1.png" @click="plusPayNum" v-if="index==payNumList.length-1 && payNumList.length<8" alt="">
                        <img src="../../../../../assets/orderPlus2.png" @click="reducePayNum(index)" v-if="index==payNumList.length-1 && payNumList.length>1" alt="">
                    </div>
                </div>
                <div class="remarksBox">
                    备注
                    <el-input
                        type="textarea"
                        style="width:500px;margin-left:20px;"
                        :rows="4"
                        placeholder="请输入备注"
                        v-model="form.pay_rule_desc">
                    </el-input>
                </div>
			</div>
            
			<!-- <div class="item" v-if="form.is_many_way==1">
				<div class="tit">应收定金</div>
				<el-input class="itemIpt" v-model="form.deposit_price" type="number"></el-input>元
			</div> -->
        </div>
        <div class="btn">
            <el-button type="primary" @click="toSubmit">处理</el-button>
        </div>
		<el-dialog title="职位选择" :visible.sync="dialogTableVisible">
			<el-table :data="personList">
				<el-table-column property="name" label="姓名" width="200"></el-table-column>
				<el-table-column property="phone" label="手机号" width="200"></el-table-column>
				<el-table-column label="操作">
					<template slot-scope="scope">
						<el-button type="primary" size="mini" @click="toSelect(scope.$index, scope.row)">选择</el-button>
					</template>
				</el-table-column>
			</el-table>
		</el-dialog>
    </div>
</template>
<script>
export default {
    data(){
        return{
            text:'处理订单',
            page:1,
            pagesize:10,

            form:{
				realname:'',
				phone:'',
				remark:'',
				estate:'',//小区
				house_type:'',//户型
				house_area:'',//面积
				address:'',
				contract_price:'',//合同金额
				deposit_price:'', //定金金额
				director:[],//负责人
				province:'',
				city:'',
				district:'',
                street:'',
				province_id:'',
				city_id:'',
				district_id:'',
                street_id:'',
                pay_rule:''
			},

            province:[],
			city:[],
			district:[],
            street:[],
			provinceObj:{},
			cityObj:{},
			districtObj:{},
            streetObj:{},
            myHeaders: {
              'access-token': this.$store.state.token  , //这里重新定义了请求头
              'Authorization': this.$store.state.token ,
              'user-id':this.$store.state.user_id
            },
			// 施工合同
            fileList1:[],
            dialogImageUrl1:'',
            dialogVisible1:false,

			// 施工图纸
            fileList:[],
            dialogImageUrl:'',
            dialogVisible:false,

			// 施工图纸
            fileList_desgin:[],
            dialogImageUrl_desgin:'',
            dialogVisible_desgin:false,

			// 选材单
            fileList_mater:[],
            dialogImageUrl_mater:'',
            dialogVisible_mater:false,

			order_id:null, //订单id
			house_keeper:{},//管家
			foreman:{},//工长
			constrTime:[],//施工时间
			personList:[],//负责人列表
			dialogTableVisible:false, //员工选择对话框
			positionType:1,//1选择管家，2选择工长
			payNumList:[{propor:60},{propor:30},{propor:10}],//支付次数与比例
        }
    },
    mounted(){
        this.order_id = this.$route.query.order_id;
		this.getProvince()
        if(this.order_id){
            this.text = '处理订单'
            this.getOrderInfo()
        }
        
        
    },
    methods:{
			// 增加支付次数
			plusPayNum(){
				this.payNumList.push({propor:0})
			},
			// 减少支付次数
			reducePayNum(index){
				this.payNumList.splice(index,1)
			},

        // 获取订单详情
        getOrderInfo(){
            let role = localStorage.getItem('role');
            let url = role=='decoration'?'/api/admin/decoration/BuildOrder/view':'/api/admin/builder/BuilderTeamOrder/view';
            this.$http.post(url,{id:this.order_id}).then(res=>{
                console.log(res,'订单详情');
                if(res.code==1){
                    this.form = res.data?res.data:{}
					let startTime = res.data.build_start_time?res.data.build_start_time:'';
					let endTime = res.data.build_end_time?res.data.build_end_time:'';
					if(startTime && endTime){
                        this.constrTime = [this.$moment(startTime*1000).format('yyyy-MM-DD'),this.$moment(endTime*1000).format('yyyy-MM-DD')]
                    }
					console.log(this.constrTime);
					console.log(res.data.director,'0000');
					if(res.data.director.length){
						this.house_keeper = res.data.director[0];
						this.foreman = res.data.director[1]
					}
				   	this.provinceObj = {
                        cityid:res.data.province_id,
                        city_name:res.data.province
                    };
                    if(res.data.province_id){
                        this.getCityList()
                    }
                    this.cityObj = {
                        cityid:res.data.city_id,
                        city_name:res.data.city
                    };
                    if(res.data.city_id){
                        this.getAreaList()
                    }
                    this.districtObj = {
                        cityid:res.data.district_id,
                        city_name:res.data.district
                    };
                    if(res.data.district_id){
                        this.getStreetList()
                    }
                    this.streetObj = {
                        cityid:res.data.street_id,
                        city_name:res.data.street
                    };

					// 合同
                    if(Array.isArray(res.data.contract_thumb_url)){
                        res.data.contract_thumb_url.map(item=>{
                            this.fileList1.push({
                                id:item.id,
                                url:item.path
                            })
                        })
                    }else{
                        this.fileList1.push({
                            id:res.data.contract_thumb_url.id,
                            url:res.data.contract_thumb_url.path
                        })
                    }

					// 图纸
					if(Array.isArray(res.data.draw_thumb_url)){
                        res.data.draw_thumb_url.map(item=>{
                            this.fileList.push({
                                id:item.id,
                                url:item.path
                            })
                        })
                    }else{
                        this.fileList.push({
                            id:res.data.draw_thumb_url.id,
                            url:res.data.draw_thumb_url.path
                        })
                    }

					// 设计图纸
					if(Array.isArray(res.data.design_thumb_url)){
                        res.data.design_thumb_url.map(item=>{
                            this.fileList_desgin.push({
                                id:item.id,
                                url:item.path
                            })
                        })
                    }else{
                        this.fileList_desgin.push({
                            id:res.data.design_thumb_url.id,
                            url:res.data.design_thumb_url.path
                        })
                    }

					// 选材单
					if(Array.isArray(res.data.material_thumb_url)){
                        res.data.material_thumb_url.map(item=>{
                            this.fileList_mater.push({
                                id:item.id,
                                url:item.path
                            })
                        })
                    }else{
                        this.fileList_mater.push({
                            id:res.data.material_thumb_url.id,
                            url:res.data.material_thumb_url.path
                        })
                    }
                }
            })
        },

		// 选择管家
		selectKeeper(){
			this.dialogTableVisible = true
			this.positionType = 1
			this.getPersonCharge()
		},

		// 选择工长
		selectForeman(){
			this.dialogTableVisible = true
			this.positionType = 2
			this.getPersonCharge()
		},

		//对话框选择
		toSelect(index,row){
			console.log(index,row,'对话框选择');
            // 一个都没选
            if(Object.keys(this.house_keeper).length<1 && Object.keys(this.foreman).length<1){
                if(this.positionType==1){
                    this.house_keeper = row
                }else{
                    this.foreman = row
                }
			    this.dialogTableVisible = false
            }else if(Object.keys(this.house_keeper).length>0 || Object.keys(this.foreman).length>0){
                if(this.positionType==1){ 
                    if(row.id==this.house_keeper.id){
                        this.dialogTableVisible = false
                        return false
                    }
                    if(row.id==this.foreman.id){
                        this.$message.warning('不可多职位')
                        return false
                    }else{
                        this.house_keeper = row
                        this.dialogTableVisible = false
                    }
                }else{
                    if(row.id==this.foreman.id){
                        this.dialogTableVisible = false
                        return false
                    }
                    if(row.id==this.house_keeper.id){
                        this.$message.warning('不可多职位')
                        return false
                    }else{
                        this.foreman = row
                        this.dialogTableVisible = false
                    }
                }
            }
		},

		// 获取成员列表
		getPersonCharge(){
            let role = localStorage.getItem('role');
			let sid = localStorage.getItem('sid')
            let key = role=='decoration'?'decoration_id':'team_id';
            let params = {
                [`${key}`]:sid
            }
            let url = role=='decoration'?'/api/admin/decoration/Builder/index':'/api/admin/builder/Builder/index';
			this.$http.post(url,params).then(res=>{
				console.log(res,'负责人列表');
				if(res.code==1){
					this.personList = res.data.list?res.data.list:[]
				}
			})
		},

		// 施工合同
        handleRemove1(file, fileList) {
            this.fileList1 = fileList
        },
        handlePictureCardPreview1(file) {
            this.dialogImageUrl1 = file.url;
            this.dialogVisible1 = true;
        },
        handleEstateSuccess1(res,file,fileList) {
            this.fileList1 = fileList
        },
        beforeAvatarUpload1(file) {
            const isLt2M = file.size / 1024 / 1024 < 2;
            if (!isLt2M) {
                this.$message.error('上传图片大小不能超过 2MB!');
            }
            return isLt2M;
        },

		// 施工图纸
        handleRemove(file, fileList) {
            this.fileList = fileList
        },
        handlePictureCardPreview(file) {
            this.dialogImageUrl = file.url;
            this.dialogVisible = true;
        },
        handleEstateSuccess(res,file,fileList) {
            this.fileList = fileList
        },
        beforeAvatarUpload(file) {
            const isLt2M = file.size / 1024 / 1024 < 2;
            if (!isLt2M) {
                this.$message.error('上传图片大小不能超过 2MB!');
            }
            return isLt2M;
        },

		// 设计图纸
        handleRemove_desgin(file, fileList) {
            this.fileList_desgin = fileList
        },
        handlePictureCardPreview_desgin(file) {
            this.dialogImageUrl_desgin = file.url;
            this.dialogVisible_desgin = true;
        },
        handleEstateSuccess_desgin(res,file,fileList) {
            this.fileList_desgin = fileList
        },
        beforeAvatarUpload_desgin(file) {
            const isLt2M = file.size / 1024 / 1024 < 2;
            if (!isLt2M) {
                this.$message.error('上传图片大小不能超过 2MB!');
            }
            return isLt2M;
        },

		// 选材单
        handleRemove_mater(file, fileList) {
            this.fileList_mater = fileList
        },
        handlePictureCardPreview_mater(file) {
            this.dialogImageUrl_mater = file.url;
            this.dialogVisible_mater = true;
        },
        handleEstateSuccess_mater(res,file,fileList) {
            this.fileList_mater = fileList
        },
        beforeAvatarUpload_mater(file) {
            const isLt2M = file.size / 1024 / 1024 < 2;
            if (!isLt2M) {
                this.$message.error('上传图片大小不能超过 2MB!');
            }
            return isLt2M;
        },

        // 省份选择
        select1(){
            this.cityObj={}
            this.districtObj={}
            this.streetObj={}
            this.getCityList()
        },
        // 城市选择
        select2(){
            this.districtObj={}
            this.streetObj={}
            if(!this.provinceObj){
                this.$message.warning('请先选择省份')
                return
            }
            this.getAreaList()
        },
        // 县区选择
        select3(){
            this.streetObj={}
            if(!this.cityObj){
                this.$message.warning('请先选择城市')
                return
            }
            this.getStreetList()
        },
        // 街道选择
        select4(){
            if(!this.districtObj){
                this.$message.warning('请先选择县区')
                return
            }
        },
        
        // 获取省份
        getProvince(){
            this.$http.post('/api/admin/base/Region/getProvinceList').then(res=>{
                console.log(res,'省份');
                if(res.code==1){
                    this.province = res.data?res.data:[]
                }
            })
        },
        // 获取城市
        getCityList(){
            this.$http.post('/api/admin/base/Region/getCityList',{province_id:this.provinceObj.cityid}).then(res=>{
                console.log(res,'城市列表');
                if(res.code==1){
                    this.city = res.data?res.data:[]
                }
            })
        },
        // 获取县区
        getAreaList(){
            this.$http.post('/api/admin/base/Region/getDistrictList',{city_id:this.cityObj.cityid}).then(res=>{
                console.log(res,'县区列表');
                if(res.code==1){
                    this.district = res.data?res.data:[]
                }
            })
        },
        // 获取街道
        getStreetList(){
            this.$http.post('/api/admin/base/region/getStreetList',{district_id:this.districtObj.cityid}).then(res=>{
                console.log(res,'街道列表');
                if(res.code==1){
                    this.street = res.data?res.data:[]
                }
            })
        },

        

		// 比例
		proporInput(index){
			console.log(index,this.payNumList,'支付比例')
			let allPropor = 0
			this.payNumList.map(item=>{
				allPropor += (item.propor*1)
			})
			console.log(allPropor,'比例之和')
			if(allPropor>100){
				this.$message.warning('比例之和为100')
                console.log(this.payNumList[index],'222');
				this.payNumList[index].propor = 0
			}
		},

        // 提交按钮
        toSubmit(){
            if(!Object.keys(this.house_keeper).length){
                this.$message.warning('请选择管家')
                return
            }
            if(!Object.keys(this.foreman).length){
                this.$message.warning('请选择工长')
                return
            }
            if(this.form.contract_price<1){
                this.$message.warning('合同金额不可低于1元')
                return
            }
			// 处理支付次数及比例
			let payArr = []
			let allPrice = 0
			this.payNumList.map(item=>{
				allPrice += (item.propor*1)
				payArr.push(item.propor/100)
			})
			for(let i = 0;i<payArr.length;i++){
				if(payArr[i]<=0){
                    this.$message.warning('请均匀分配100%比例')
					return
				}
			}
			console.log(allPrice,'总比例')
			console.log(payArr,'比例数组')
			if(allPrice!=100){
                this.$message.warning('支付次数比例之和必须等于100')
				return
			}
            console.log(this.house_keeper,this.foreman,'---');
			let position = [{builder_id:this.house_keeper.id,position:1},{builder_id:this.foreman.id,position:2}]
			position = JSON.stringify(position)
			let startTime = this.$moment(this.constrTime[0]).format('yyyy-MM-DD')
			let endTime = this.$moment(this.constrTime[1]).format('yyyy-MM-DD')
			console.log(startTime);
			this.form.build_start_time = startTime;
			this.form.build_end_time = endTime;

			this.form.director = position;
			this.form.province = this.provinceObj.city_name;
			this.form.city = this.cityObj.city_name;
			this.form.district = this.districtObj.city_name;
            this.form.street = this.streetObj.city_name;
			this.form.province_id = this.provinceObj.cityid;
			this.form.city_id = this.cityObj.cityid;
			this.form.district_id = this.districtObj.cityid;
			this.form.street_id = this.streetObj.cityid;
			this.form.pay_rule = payArr.join(',');
			
			// 施工合同
			let contract = []
			this.fileList1.map(item=>{
				if(item.response){
					contract.push(item.response.data.id)
				}else{
					contract.push(item.id)
				}
			})
			// 施工图纸
			let drawing = []
			this.fileList.map(item=>{
				if(item.response){
					drawing.push(item.response.data.id)
				}else{
					drawing.push(item.id)
				}
			})
			// 设计图纸
			let desgin = []
			this.fileList_desgin.map(item=>{
				if(item.response){
					desgin.push(item.response.data.id)
				}else{
					desgin.push(item.id)
				}
			})
			// 选材单
			let mater = []
			this.fileList_mater.map(item=>{
				if(item.response){
					mater.push(item.response.data.id)
				}else{
					mater.push(item.id)
				}
			})
			this.form.contract_thumb_url = contract.join(',')
			this.form.draw_thumb_url = drawing.join(',')
            this.form.material_thumb_url = mater.join(',')
            this.form.design_thumb_url = desgin.join(',')
			console.log(this.form,'处理提交数据');
			this.$http.post('/api/admin/builder/BuilderTeamOrder/handle',this.form).then(res=>{
				console.log(res,'处理结果');
				if(res.code==1){
					this.$message.success('处理成功')
					this.$router.back(1)
				}else{
					this.$message.warning(res.msg)
				}
			})
        },

        // 返回
        toBack(){
            this.$router.back(1)
        },
    }
}
</script>

<style lang="less">
    @import 'detail.less';
</style>


